package sein.android.hopenote;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import sein.android.hopenote.Const.HopeNoteDb;
import android.R.array;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mocoplex.adlib.AdlibActivity;


public class Note_Day extends AdlibActivity {
	
	private DBAdapter HnopenHelper;
	private SQLiteDatabase sdb;
	private String str_User;
	private	Cursor list_cur;
	private EditText et_date;
	private Button btn_yesterday, btn_tommorow;
	private	ListView lv_search;
	private	ArrayList<SearchData> Search_arr;
	private SearchAdapter S_adapter;
	private int iYear, iMonth, iDay;
	static final int DATE_DIALOG_ID = 0;
	private View v_et;
	private String mSdPath;
	private Calendar cal;
	private SimpleDateFormat dateformat;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.note_day);
		
		IntentFilter filter_reset = new IntentFilter("Reset");
		registerReceiver(BR_Note_Day,filter_reset);
		IntentFilter filter_fileout = new IntentFilter("Fileout_day");
		registerReceiver(BR_Note_Day_Fileout,filter_fileout);
		IntentFilter filter_Emailout = new IntentFilter("Emailout_day");
		registerReceiver(BR_Note_Day_Emailout,filter_Emailout);
		
		HnopenHelper = new DBAdapter(this);
        sdb = HnopenHelper.getReadableDatabase();
        
        str_User = "";
        
		et_date  = (EditText)findViewById(R.id.et_date);
		btn_yesterday = (Button)findViewById(R.id.btn_yesterday);
		btn_tommorow = (Button)findViewById(R.id.btn_tommorow);
		
        str_User = HopeNoteDb.CURRENT_USER;	// 사용자 명
		
		// 광고 호출
		this.setAdsContainer(R.id.ads);
		
		cal = new GregorianCalendar();
		dateformat = new SimpleDateFormat("yyyy-MM-dd");
		Date date = cal.getTime();
		
		et_date.setText(dateformat.format(date));
		cal.add(Calendar.DAY_OF_MONTH, 1);
		date = cal.getTime();
		btn_tommorow.setText(dateformat.format(date));
		cal.add(Calendar.DAY_OF_MONTH, -2);
		date = cal.getTime();
		btn_yesterday.setText(dateformat.format(date));
				
		DateTimeInit();
		
		// DB
		String dateString = et_date.getText().toString();
		String dateStringA = dateString;
		Cursor day_cur;
		ArrayList<String> TableFormat = new ArrayList<String>();
		
		try {
			date = dateformat.parse(dateString);
			cal.setTime(date);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		int limit = 7, sum = 0;

		while(true)
		{
			String checkquery = "SELECT	count(" + HopeNoteDb.COL_DOCUMENT1 +")" +
							" FROM "+ HopeNoteDb.TB_NOTE + " " +
							" WHERE " + HopeNoteDb.COL_USER + " = '" + str_User + 
									"' AND strftime('%Y-%m-%d'," + HopeNoteDb.COL_DATE + ") = '" + dateStringA + "'" + 
						" GROUP BY " + HopeNoteDb.COL_ITEM + ";";
			
			day_cur = sdb.rawQuery(checkquery, null);
			
			int maxcnt = 0;
			
			if(day_cur.getCount() > 0)
			{
				day_cur.moveToFirst();
				for(int x=0; x<day_cur.getCount(); x++)
				{
					if(maxcnt < day_cur.getInt(0))
						maxcnt = day_cur.getInt(0);
					day_cur.moveToNext();
				}
								
				sum += maxcnt;
				
				for(int c=0; c < maxcnt && TableFormat.size() < 3; c++)
				{
					TableFormat.add(dateStringA);
				}
			}
			
			if( sum > 2 || limit == 0 )
				break;

			cal.add(Calendar.DAY_OF_MONTH, -1);
			date = cal.getTime();
			dateStringA = dateformat.format(date);
			
			limit--;
		}

		String first = "-",second = "-",third = "-";
		if(TableFormat.size() > 0)
		{
			first = TableFormat.get(0).substring(8) + "일";
		}
		if(TableFormat.size() > 1)
		{
			second = TableFormat.get(1).substring(8) + "일";
		}
		if(TableFormat.size() > 2)
		{
			third = TableFormat.get(2).substring(8) + "일";
		}

		String query = "SELECT "+ HopeNoteDb.COL_ITEM +", "
						+ HopeNoteDb.COL_DOCUMENT1 +", "
						+ HopeNoteDb.COL_DOCUMENT2 +", " +
						"strftime('%d'," + HopeNoteDb.COL_DATE +") || '일'" +
				" FROM "+ HopeNoteDb.TB_NOTE + " " +
				" WHERE " + HopeNoteDb.COL_USER + " = '" + str_User + 
						"' AND strftime('%Y-%m-%d'," + HopeNoteDb.COL_DATE + ") between '" + dateStringA + "' and '" + dateString + 
			"' ORDER BY " + HopeNoteDb.COL_ITEM + ", " + HopeNoteDb.COL_DATE + " DESC;";
		
		list_cur = sdb.rawQuery(query, null);
		
		list_cur.moveToFirst();
        
        // Insert into Array
        Search_arr = new ArrayList<SearchData>();
        Search_arr.add(new SearchData("항목",third,second,"최근"));
        //SearchData datarow;
        ArrayList<String> documents = new ArrayList<String>();
        String itemname, values;
        for(int i = 0; i < list_cur.getCount(); i++){
        	
        	itemname = list_cur.getString(0);
        	
        	values = list_cur.getString(2);
        	
        	if(values.equals(""))
        	{
        		values = list_cur.getString(1);
        	}
        	else
        	{
        		values = list_cur.getString(1) + "/" + list_cur.getString(2);
        	}
        	
        	if(documents.size() < 3)
        	{
	        	if(list_cur.getString(3).equals(first) && documents.size() == 0)
	        	{
	        		documents.add(values);
	        	}
	        	else if(list_cur.getString(3).equals(second) && documents.size() == 1)
	        	{
	        		documents.add(values);
	        	}
	        	else if(list_cur.getString(3).equals(third) && documents.size() == 2)
	        	{
	        		documents.add(values);
	        	}
	        	else
	        	{
	        		documents.add("-");
	        	}
        	}
        	
        	list_cur.moveToNext();
        	
        	if(list_cur.isAfterLast())
        	{
        		
        		if(documents.size() == 1)
        		{
        			documents.add("-");
        			documents.add("-");
        		}
        		else if(documents.size() == 2)
        		{
        			documents.add("-");
        		}
        		Search_arr.add(new SearchData(itemname, documents.get(2), documents.get(1), documents.get(0)));
        		documents.clear();
        	}
        	else if(!itemname.equals(list_cur.getString(0)))
        	{

        		if(documents.size() == 1)
        		{
        			documents.add("-");
        			documents.add("-");
        		}
        		else if(documents.size() == 2)
        		{
        			documents.add("-");
        		}
        		Search_arr.add(new SearchData(itemname, documents.get(2), documents.get(1), documents.get(0)));
        		
        		documents.clear();
        	}
        }
        list_cur.close();
        
        // Custom Adapter
        S_adapter = new SearchAdapter(this, R.layout.note_day_row,Search_arr);
        
        lv_search = (ListView)findViewById(R.id.lv_day);
        lv_search.setAdapter(S_adapter);
        
        
        // 년/월 자동완
        et_date.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
				// UI 날짜 변
				SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
				Date date = null;
				try {
					date = dateformat.parse(s.toString());
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				cal.setTime(date);
				cal.add(Calendar.DAY_OF_MONTH, 1);
				date = cal.getTime();
				btn_tommorow.setText(dateformat.format(date));
				cal.add(Calendar.DAY_OF_MONTH, -2);
				date = cal.getTime();
				btn_yesterday.setText(dateformat.format(date));
				
				// 환경 설정 확인
				if(HopeNoteDb.CURRENT_USER.equals(""))
				{
					Toast.makeText(Note_Day.this, "메뉴키를 눌러 사용자를 선택해주세요.", Toast.LENGTH_SHORT).show();
				}
				
				// 새로고침
				else
				{
					reset();
				}
			}
		});
        
        // DatePicker
        et_date.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				v_et = v;
				showDialog(DATE_DIALOG_ID);
			}
		});
        
        // 하루 전 버튼
        btn_yesterday.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				et_date.clearFocus();
				
				String date = btn_yesterday.getText().toString();
				
				et_date.setText(date);
				
			}
		});
        
        // 다음 날 버튼
        btn_tommorow.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				et_date.clearFocus();
				
				String date = btn_tommorow.getText().toString();
				
				et_date.setText(date);
			}
		});
	}
	
	
	//검색 결과 (날짜/값) 데이터 클래스
	class SearchData{
		String item;
		String document1;
		String document2;
		String document3;
		SearchData(String _item, String _document1, String _document2, String _document3){
			item = _item;
			document1 = _document1;
			document2 = _document2;
			document3 = _document3;
		}
	}
	
	//검색 결과 어댑터 클래스
	class SearchAdapter extends BaseAdapter{
		Context context;
		int layoutId;
		ArrayList<SearchData> ResultDataArr;
		LayoutInflater Inflater;
		SearchAdapter(Context _context, int _layoutId, ArrayList<SearchData> _ResultDataArr){
			context = _context;
			layoutId = _layoutId;
			ResultDataArr = _ResultDataArr;
			Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		public int getCount(){
			return ResultDataArr.size();
		}
		
		public Object getItem(int position){
			return ResultDataArr.get(position);
		}
		
		public long getItemId(int position)
		{
			return position;
		}
		
		public View getView(int position, View convertView, ViewGroup parent){
			//final int pos = position;
			if(convertView == null){
				convertView = Inflater.inflate(layoutId, parent,false);
			}
			
			TextView tv_item = (TextView)convertView.findViewById(R.id.tv_item);
			TextView tv_document1 = (TextView)convertView.findViewById(R.id.tv_document1);
			TextView tv_document2 = (TextView)convertView.findViewById(R.id.tv_document2);
			TextView tv_document3 = (TextView)convertView.findViewById(R.id.tv_document3);
			
			tv_item.setText(ResultDataArr.get(position).item);
			tv_document1.setText(ResultDataArr.get(position).document1);
			tv_document2.setText(ResultDataArr.get(position).document2);
			tv_document3.setText(ResultDataArr.get(position).document3);

			/*
			convertView.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
				}
			});
			*/
			
			return convertView;
		}
	}
	
	
	private void reset() {
		// TODO Auto-generated method stub
		str_User = HopeNoteDb.CURRENT_USER;
		list_cur.close();
		
		// DB
		String dateString = et_date.getText().toString();
		String dateStringA = dateString;
		Cursor day_cur;
		ArrayList<String> TableFormat = new ArrayList<String>();
		Date date;
		
		try {
			date = dateformat.parse(dateString);
			cal.setTime(date);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		int limit = 7, sum = 0;
		while(true)
		{
			Log.i("check", dateStringA);
			String checkquery = "SELECT	count(" + HopeNoteDb.COL_DOCUMENT1 +")" +
							" FROM "+ HopeNoteDb.TB_NOTE + " " +
							" WHERE " + HopeNoteDb.COL_USER + " = '" + str_User + 
									"' AND strftime('%Y-%m-%d'," + HopeNoteDb.COL_DATE + ") = '" + dateStringA + "'" + 
							" GROUP BY " + HopeNoteDb.COL_ITEM + ";";
			
			day_cur = sdb.rawQuery(checkquery, null);
			
			int maxcnt = 0;
			
			if(day_cur.getCount() > 0)
			{
				day_cur.moveToFirst();
				for(int x=0; x<day_cur.getCount(); x++)
				{
					if(maxcnt < day_cur.getInt(0))
						maxcnt = day_cur.getInt(0);
					day_cur.moveToNext();
				}
				
				Log.i("check",String.valueOf(maxcnt));
				
				sum += maxcnt;
				
				Log.i("check",String.valueOf(sum));
				
				for(int c=0; c < maxcnt && TableFormat.size() < 3; c++)
				{
					TableFormat.add(dateStringA);
				}
			}
			
			if( sum > 2 || limit == 0 )
				break;
		
			cal.add(Calendar.DAY_OF_MONTH, -1);
			date = cal.getTime();
			dateStringA = dateformat.format(date);
			
			limit--;
		}
		
		String first = "-",second = "-",third = "-";
		if(TableFormat.size() > 0)
		{
			first = TableFormat.get(0).substring(8) + "일";
		}
		if(TableFormat.size() > 1)
		{
			second = TableFormat.get(1).substring(8) + "일";
		}
		if(TableFormat.size() > 2)
		{
			third = TableFormat.get(2).substring(8) + "일";
		}
		
		Log.i("check",first);
		Log.i("check",second);
		Log.i("check",third);
		
		String query = "SELECT "+ HopeNoteDb.COL_ITEM +", "
						+ HopeNoteDb.COL_DOCUMENT1 +", "
						+ HopeNoteDb.COL_DOCUMENT2 +", " +
						"strftime('%d'," + HopeNoteDb.COL_DATE +") || '일'" +
				" FROM "+ HopeNoteDb.TB_NOTE + " " +
				" WHERE " + HopeNoteDb.COL_USER + " = '" + str_User + 
						"' AND strftime('%Y-%m-%d'," + HopeNoteDb.COL_DATE + ") between '" + dateStringA + "' and '" + dateString + 
			"' ORDER BY " + HopeNoteDb.COL_ITEM + ", " + HopeNoteDb.COL_DATE + " DESC;";
		
		Log.i("check",query);
		
		list_cur = sdb.rawQuery(query, null);
		
		list_cur.moveToFirst();
		
		// Insert into Array
		//Search_arr = new ArrayList<SearchData>();
		Search_arr.clear();
		Search_arr.add(new SearchData("항목",third,second,"최근"));
		//SearchData datarow;
		ArrayList<String> documents = new ArrayList<String>();
		String itemname, values;
		for(int i = 0; i < list_cur.getCount(); i++){
			
			itemname = list_cur.getString(0);
			
			values = list_cur.getString(2);
			
			if(values.equals(""))
			{
				values = list_cur.getString(1);
			}
			else
			{
				values = list_cur.getString(1) + "/" + list_cur.getString(2);
			}
			
			if(documents.size() < 3)
			{
		    	if(list_cur.getString(3).equals(first) && documents.size() == 0)
		    	{
		    		documents.add(values);
		    	}
		    	else if(list_cur.getString(3).equals(second) && documents.size() == 1)
		    	{
		    		documents.add(values);
		    	}
		    	else if(list_cur.getString(3).equals(third) && documents.size() == 2)
		    	{
		    		documents.add(values);
		    	}
		    	else
		    	{
		    		documents.add("-");
		    	}
			}
			
			list_cur.moveToNext();
			
			if(list_cur.isAfterLast())
			{
				
				if(documents.size() == 1)
				{
					documents.add("-");
					documents.add("-");
				}
				else if(documents.size() == 2)
				{
					documents.add("-");
				}
				Search_arr.add(new SearchData(itemname, documents.get(2), documents.get(1), documents.get(0)));
				documents.clear();
			}
			else if(!itemname.equals(list_cur.getString(0)))
			{
		
				if(documents.size() == 1)
				{
					documents.add("-");
					documents.add("-");
				}
				else if(documents.size() == 2)
				{
					documents.add("-");
				}
				Search_arr.add(new SearchData(itemname, documents.get(2), documents.get(1), documents.get(0)));
				
				documents.clear();
			}
		}
		list_cur.close();

        S_adapter.notifyDataSetChanged();
	}
	
	public void DateTimeInit()
	{
		final Calendar objTime = Calendar.getInstance();
        iYear = objTime.get(Calendar.YEAR);
        iMonth = objTime.get(Calendar.MONTH);
        iDay = objTime.get(Calendar.DAY_OF_MONTH);
	}
	
	protected Dialog onCreateDialog(int id)
	{
		switch(id)
		{
		case DATE_DIALOG_ID:
			return new DatePickerDialog(getParent(), mDateSetListener, iYear, iMonth, iDay);
		}
		return null;
	}
	
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// TODO Auto-generated method stub
			iYear = year;
			iMonth = monthOfYear;
			iDay = dayOfMonth;
			
			if(v_et.getId() == R.id.et_date)
			{
				updateDisplay(et_date);
			}
		}
	};
	
	private void updateDisplay(EditText et)
	{
		String tMon, tDay;
		tMon = Integer.toString(iMonth+1);
		tDay = Integer.toString(iDay);
		if(tMon.length() == 1)
		{
			tMon = "0" + tMon;
		}
		if(tDay.length() == 1)
		{
			tDay = "0" + tDay;
		}
		
		et.setText(new StringBuilder().append(iYear).append("-").append(tMon).append("-").append(tDay));
	}
		
	private BroadcastReceiver BR_Note_Day = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
	        reset();
		}
	};
	
	//csv file output
	private BroadcastReceiver BR_Note_Day_Fileout = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			
			StringBuilder sb = new StringBuilder();
			
			String ext = Environment.getExternalStorageState();
			if(ext.equals(Environment.MEDIA_MOUNTED)){
				mSdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
			}else{
				mSdPath = Environment.MEDIA_UNMOUNTED;
			}
			
			try{				
				// directory 생성
				File dir = new File(mSdPath + "/hopenote");
				dir.mkdir();
				
				// 파일 생성
				SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
				Date date = new Date();
				String szFileName = "최근기록_"+et_date.getText().toString().replace("-", "")+"_"+dateformat.format(date)+".csv";
				File file = new File(mSdPath + "/hopenote/" + szFileName);
				
				if (!file.exists()){
	            	mSdPath = "";
	            }else{
	            	AlertDialog.Builder ad = new AlertDialog.Builder(Note_Day.this);
	            	ad.setMessage("파일 생성 실패");
	            	ad.setPositiveButton(android.R.string.ok, null);
	            	ad.setTitle("Error");
	            	ad.show();
	            	return;
	            }
				
	            WritableWorkbook workbook = null;
	     	    WritableSheet sheet = null;
	
	     	   
	     	    try{
	     	    	
					//FileOutputStream fos = new FileOutputStream(file);
					//FileOutputStream excelFile = openFileOutput(szFileName, Context.MODE_WORLD_WRITEABLE);
					sb.append("success create file");
	
		        	
    	            //workbook = Workbook.createWorkbook(excelFile);
	        		workbook = Workbook.createWorkbook(file);
    	            workbook.createSheet("sheet1", 0);
    	            sheet = workbook.getSheet(0);
	                sheet.addCell(new Label(0, 0, "항목별 최근 기록"));
	                
	                // DB
	        		//list_cur.moveToFirst();
    	            
    	            // Insert into Array
	        		SearchData datarow;
    	            for(int i = 0; i < Search_arr.size(); i++){
    	            	
    	            	datarow = Search_arr.get(i);
    	            	
    	            	sheet.addCell(new Label(0, i+1, datarow.item));
    	                sheet.addCell(new Label(1, i+1, datarow.document1));
    	                sheet.addCell(new Label(2, i+1, datarow.document2));
    	                sheet.addCell(new Label(3, i+1, datarow.document3));
    	                
    	            }

    	            workbook.write();
    	            workbook.close();
    	            
    	            Toast.makeText(Note_Day.this, "hopenote/"+szFileName+" 저장 완료", Toast.LENGTH_LONG).show();
					
				}catch(FileNotFoundException e){
					sb.append("========file not found err : " + e.toString());
				}catch(SecurityException e){
					sb.append("========Security Exception  err: " + e.toString());
				}catch(Exception e){
					sb.append("======== Exception  err: " + e.toString());
				}
				
			}catch(Exception e){
				sb.append("btn_write_test err : " + e.toString() );
			}
			Log.i("log",sb.toString());
		}
	};
	
	
	//csv file to Email
		private BroadcastReceiver BR_Note_Day_Emailout = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				
				StringBuilder sb = new StringBuilder();
				
				String ext = Environment.getExternalStorageState();
				if(ext.equals(Environment.MEDIA_MOUNTED)){
					mSdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
				}else{
					mSdPath = Environment.MEDIA_UNMOUNTED;
				}
				
				try{				
					// directory 생성
					File dir = new File(mSdPath + "/hopenote");
					dir.mkdir();
					// 파일 생성
					SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
					Date date = new Date();
					String szFileName = "최근기록_"+et_date.getText().toString().replace("-", "")+"_"+dateformat.format(date)+".csv";
					File file = new File(mSdPath + "/hopenote/" + szFileName);

					if (!file.exists()){
		            	mSdPath = "";
		            }else{
		            	AlertDialog.Builder ad = new AlertDialog.Builder(Note_Day.this);
		            	ad.setMessage("파일 생성 실패");
		            	ad.setPositiveButton(android.R.string.ok, null);
		            	ad.setTitle("Error");
		            	ad.show();
		            	return;
		            }
					
		            WritableWorkbook workbook = null;
		     	    WritableSheet sheet = null;
		
		     	   
		     	    try{
		     	    	
						//FileOutputStream fos = new FileOutputStream(file);
						//FileOutputStream excelFile = openFileOutput(szFileName, Context.MODE_WORLD_WRITEABLE);
						sb.append("success create file");
		
			        	//workbook = Workbook.createWorkbook(excelFile);
		        		workbook = Workbook.createWorkbook(file);
	    	            workbook.createSheet("sheet1", 0);
	    	            sheet = workbook.getSheet(0);
	    	            sheet.addCell(new Label(0, 0, "항목별 최근 기록"));
		                
		                // DB
		        		//list_cur.moveToFirst();
	    	            
	    	            // Insert into Array
		        		SearchData datarow;
	    	            for(int i = 0; i < Search_arr.size(); i++){
	    	            	
	    	            	datarow = Search_arr.get(i);
	    	            	
	    	            	sheet.addCell(new Label(0, i+1, datarow.item));
	    	                sheet.addCell(new Label(1, i+1, datarow.document1));
	    	                sheet.addCell(new Label(2, i+1, datarow.document2));
	    	                sheet.addCell(new Label(3, i+1, datarow.document3));
	    	                
	    	            }

	    	            workbook.write();
	    	            workbook.close();
	    	            
	    	            Toast.makeText(Note_Day.this, "hopenote/"+szFileName+" 저장 완료", Toast.LENGTH_LONG).show();
						
					}catch(FileNotFoundException e){
						sb.append("========file not found err : " + e.toString());
					}catch(SecurityException e){
						sb.append("========Security Exception  err: " + e.toString());
					}catch(Exception e){
						sb.append("======== Exception  err: " + e.toString());
					}
		     	    
		     	    Uri fileUri = Uri.fromFile(file);
					
		     	   Intent it = new Intent(Intent.ACTION_SEND);
					it.setType("plane/text");
					
					// 수신인 주소 - tos배열의 값을 늘릴 경우 다수의 수신자에게 발송됨
					//String[] tos = { "h_zilla@hotmail.com" };
					//it.putExtra(Intent.EXTRA_EMAIL, tos);
					it.putExtra(Intent.EXTRA_SUBJECT, "");
					it.putExtra(Intent.EXTRA_TEXT, "");
					it.putExtra(Intent.EXTRA_STREAM, fileUri);
					startActivity(it);
		     	    
				}catch(Exception e){
					sb.append("btn_write_test err : " + e.toString() );
				}
				Log.i("log",sb.toString());
			}
		};
		
	
	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub
		super.onAttachedToWindow();

		reset();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(BR_Note_Day);
		unregisterReceiver(BR_Note_Day_Fileout);
		unregisterReceiver(BR_Note_Day_Emailout);
		list_cur.close();
	};
}
